package com.danawa.watcher.util;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;


public class PageUtil {

	private static void callPage(HttpServletResponse res, String msg) throws IOException {
		res.setContentType("text/html; charset=utf-8");
		PrintWriter pw = res.getWriter();
		try {
			pw.println(msg);
		} finally {
			if (pw != null)
				pw.close();
		}
	}

	/**
	 * Alert창을 띄운 후, 페이지를 history.back 한다
	 *
	 * @param res
	 * @param alertMsg
	 * @throws IOException
	 */
	public static void historyBack(HttpServletResponse res, String alertMsg) throws IOException {
		alertMsg = HTMLUtil.toJS(alertMsg);
		callPage(res, "<script>alert(\"" + alertMsg + "\"); this.history.back(-1);</script>");
	}
	
	/**
	 *  정해진 곳으로 Forward를 시킴
	 *
	 * @param res
	 * @param alertMsg
	 * @param forwardUrl
	 * @throws IOException
	 */
	public static void forward(HttpServletResponse res, String forwardUrl) throws IOException {
		StringBuffer sb = new StringBuffer();
        sb.append("<meta http-equiv=\"Refresh\" content=\"0; url=").append( forwardUrl ).append("\">");
		callPage(res, sb.toString());
	}
	
	/**
	 * Alert창을 띄운 후, 정해진 곳으로 Forward를 시킴
	 *
	 * @param res
	 * @param alertMsg
	 * @param forwardUrl
	 * @throws IOException
	 */
	public static void alertAndForward(HttpServletResponse res, String alertMsg, String forwardUrl) throws IOException {
		alertMsg = HTMLUtil.toJS(alertMsg);
		StringBuffer sb = new StringBuffer();
		sb.append("<script> alert(\"").append(alertMsg).append("\");</script>")
		        .append("<meta http-equiv=\"Refresh\" content=\"0; url=").append(
		            forwardUrl).append("\">");

		callPage(res, sb.toString());
	}
}
